package com.itheima.wms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.ImmutableMap;
import com.itheima.pinda.exception.BizException;
import com.itheima.wms.common.enums.*;
import com.itheima.wms.common.service.CrudServiceImpl;
import com.itheima.wms.dao.*;
import com.itheima.wms.dto.ReceiptListBatchDTO;
import com.itheima.wms.dto.ReceiptListDTO;
import com.itheima.wms.entity.*;
import com.itheima.wms.service.ReceiptListService;
import com.itheima.wms.service.StockService;
import com.itheima.wms.vo.ReceiptListDetailVO;
import com.itheima.wms.vo.ReceiptListSumVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 业务实现类
 * 入库清单
 * </p>
 */
@Slf4j
@Service
public class ReceiptListServiceImpl extends CrudServiceImpl<ReceiptListMapper, ReceiptListEntity> implements ReceiptListService {

    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private ReceiptMapper receiptMapper;
    @Autowired
    private ReceivingMapper receivingMapper;
    @Autowired
    private GroundingMapper groundingMapper;
    @Autowired
    private StockService stockService;
    @Autowired
    private StockRecordMapper stockRecordMapper;
    @Autowired
    private LocationMapper locationMapper;
    @Autowired
    private LocationPlanMapper locationPlanMapper;
    @Autowired
    private OwnerLocationMapper ownerLocationMapper;

    @Override
    @Transactional
    public Boolean saveBatchByGoodsIds(ReceiptListBatchDTO receiptListBatchDTO) {
        List<GoodsEntity> goodsEntities = goodsMapper.selectBatchIds(receiptListBatchDTO.getGoodsIds());
        ReceiptEntity receiptEntity = receiptMapper.selectById(receiptListBatchDTO.getMasterId());
        List<ReceiptListEntity> receiptListEntities = new ArrayList<>();
        for (GoodsEntity goodsEntity : goodsEntities) {

            ReceiptListEntity receiptListEntity = ReceiptListEntity.builder()
                    .masterId(receiptListBatchDTO.getMasterId())
                    .goodsId(goodsEntity.getId())
                    .ownerId(goodsEntity.getOwnerId())
                    .warehouseId(receiptEntity.getWarehouseId())
                    .recommendAreaId(receiptEntity.getAreaId())
                    .recommendLocationPlanId(null)
                    .build();
            receiptListEntities.add(receiptListEntity);

        }
        return this.saveBatch(receiptListEntities);
    }

    /**
     * 根据货主的上架策略，系统给推荐库位。
     * 如果没有符合的上架策略，则按以下逻辑推荐：
     * 在货主的使用库位范围内，寻找存储类型库区，按以下规则上架：
     * 1.货品有指定库位上指定不满库位，否则上指定库位的空库位
     * 2.货品没有指定库位，根据一品一位的原则，搜索是否有此货品的未满的库位，优先放未满库位
     * 3，否则选择空库位放货品，按照库位号大小依次上架
     *
     * @param id
     */
    @Override
    @Async
    public void buildLocationPlanByReceipt(Long id) {
        LambdaQueryWrapper<ReceiptListEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ReceiptListEntity::getMasterId, id);
        List<ReceiptListEntity> receiptListEntities = this.baseMapper.selectList(queryWrapper);

        receiptListEntities.forEach(receiptListEntity -> {
            GoodsEntity goodsEntity = goodsMapper.selectById(receiptListEntity.getGoodsId());
            buildLocationPlan(goodsEntity, receiptListEntity);
        });
    }

    /**
     * 构建单个货品的方案
     *
     * @param goodsEntity
     * @param receiptListEntity
     */
    private void buildLocationPlan(GoodsEntity goodsEntity, ReceiptListEntity receiptListEntity) {
        // 库位方案集合
        List<LocationPlanEntity> locationPlanEntities = new ArrayList<>();
        // 方案id
        Long locationPlanId = IdWorker.getId();
        // 货品体积
        BigDecimal goodsVolume = goodsEntity.getVolume();
        // 待入库货品总数量
        Integer planNum = receiptListEntity.getRealNum();

        // 当前货主当前货品可以使用的库位信息 （包含空闲 和 未满的库位）
        List<LocationEntity> locationEntities = getLocationListByGoodsAndIds(goodsEntity);
        log.info("\n构建当前清单的推荐库位:{} \n方案id:{} \n货品信息:{} \n可用库位:{}", receiptListEntity, locationPlanId, goodsEntity, locationEntities);

        Iterator<LocationEntity> locationEntitiesIt = locationEntities.iterator();
        log.info("进入while 循环：{} {}", locationEntitiesIt.hasNext(), planNum);
        while (locationEntitiesIt.hasNext() && planNum > 0) { // 入库数量不为空的时候才会进入循环
            LocationEntity locationEntity = locationEntitiesIt.next();
            log.info("遍历到库位:{} 剩余入库数量:{}", locationEntity, planNum);

            // 库位最大体积
            BigDecimal maxVolume = locationEntity.getMaxVolume();
            // 库存已使用个数
            int useNum = getUseNumByLocation(locationEntity);
            // 当前库位还可以存放的数量  （库位体积 ÷ 货品体积  - 已存在数量）
            int freeNum = maxVolume.divide(goodsVolume, 2, BigDecimal.ROUND_HALF_UP).intValue() - useNum;
            if (freeNum <= 0) {
                log.info("当前库位已满:{}", locationEntity.getId());
                continue;
            }
            // 本次存放的数量
            int currentNum = planNum;
            if (freeNum < planNum) { // 空闲不足
                // 空闲的位置无法放入全部货品  则放满即可
                currentNum = freeNum;
            }
            log.info("方案基础信息 planNum:{} maxVolume:{} useNum:{} freeNum:{} currentNum:{}", planNum, maxVolume, useNum, freeNum, currentNum);
            LocationPlanEntity locationPlanEntity = LocationPlanEntity.builder()
                    .num(currentNum)// 存放数量
                    .groupId(locationPlanId)
                    .warehouseId(locationEntity.getWarehouseId())
                    .areaId(locationEntity.getAreaId())
                    .locationId(locationEntity.getId())//匹配到库位id
                    .receiptListId(receiptListEntity.getId())
                    .createTime(LocalDateTime.now())
                    .build();
            locationPlanEntities.add(locationPlanEntity);
            locationPlanMapper.insert(locationPlanEntity);
            // 去除已匹配到库位的数量
            planNum -= currentNum;
        }
        log.info("方案构建完成:{}", locationPlanEntities);

        // 保存入库
        if (!CollectionUtils.isEmpty(locationPlanEntities)) {
            receiptListEntity.setRecommendAreaId(locationPlanEntities.get(0).getAreaId());
        }
        receiptListEntity.setRecommendLocationPlanId(locationPlanId);
        this.baseMapper.updateById(receiptListEntity);

    }

    /**
     * 根据商品信息查询
     *
     * @param goodsEntity
     * @return
     */
    private List<LocationEntity> getLocationListByGoodsAndIds(GoodsEntity goodsEntity) {
        // 查询货主可以使用的库位
        List<Long> locationIds = getLocationIdsByGoods(goodsEntity);
        if (locationIds == null) {
            // 没有可用库位
            return new ArrayList<>();
        }

        LambdaQueryWrapper<LocationEntity> locationWrapper = new LambdaQueryWrapper();
        locationWrapper.eq(null != goodsEntity.getWarehouseId(), LocationEntity::getWarehouseId, goodsEntity.getWarehouseId());
        locationWrapper.eq(null != goodsEntity.getAreaId(), LocationEntity::getAreaId, goodsEntity.getAreaId()); // 指定库区
        locationWrapper.eq(null != goodsEntity.getTemperatureType(), LocationEntity::getTemperatureType, goodsEntity.getTemperatureType());
        locationWrapper.eq(null != goodsEntity.getBearingType(), LocationEntity::getBearingType, goodsEntity.getBearingType());
        locationWrapper.eq(LocationEntity::getUseType, "CCQ");
        locationWrapper.eq(LocationEntity::getStatus, LocationStatus.ENABLE.getCode());
        locationWrapper.eq(LocationEntity::getFrozen, LocationFrozen.NORMAL.getCode());
        locationWrapper.ne(LocationEntity::getUseStatus, LocationUseStatus.FULL.getCode()); // 排除已满的状态
        locationWrapper.in(LocationEntity::getId, locationIds);
        locationWrapper.orderByAsc(LocationEntity::getUseStatus, LocationEntity::getCode); // 排序 优先用未满的 再用空闲的

        List<LocationEntity> locationEntities = locationMapper.selectList(locationWrapper);
        log.info("当前货主:{},可用的库位:{}", goodsEntity.getOwnerId(), locationEntities);
        return locationEntities == null ? new ArrayList<>() : locationEntities;
    }

    /**
     * 根据库位查询是否有余量
     *
     * @param locationEntity
     * @return
     */
    private Integer getUseNumByLocation(LocationEntity locationEntity) {
        // 如果库位不是空闲状态 查询库存的余量
        if (0 != locationEntity.getUseStatus()) {
            StockEntity stockEntity = stockService.getOneByLocationId(locationEntity.getId());
            log.info("根据库位:{}，查询库存信息:{}", locationEntity.getId(), stockEntity);
            if (null != stockEntity) {
                return stockEntity.getTotal();
            }
        }
        return 0;
    }

    /**
     * 根据货品的货主信息查询库位id集合
     *
     * @param goodsEntity
     * @return
     */
    private List<Long> getLocationIdsByGoods(GoodsEntity goodsEntity) {
        // 获取货主id
        Long ownerId = goodsEntity.getOwnerId();
        // 货品指定库区 (可能为空)
        Long areaId = goodsEntity.getAreaId();
        LambdaQueryWrapper<OwnerLocationEntity> ownerLocationWrapper = new LambdaQueryWrapper<>();
        ownerLocationWrapper.eq(OwnerLocationEntity::getOwnerId, ownerId);
        ownerLocationWrapper.eq(null != areaId, OwnerLocationEntity::getAreaId, areaId); // 2.货品没有指定库位，根据一品一位的原则，搜索是否有此货品的未满的库位，优先放未满库位
        List<OwnerLocationEntity> ownerLocationEntities = ownerLocationMapper.selectList(ownerLocationWrapper);
        if (CollectionUtils.isEmpty(ownerLocationEntities)) {
            if (null != areaId) {
                log.warn("当前货主:{} 没有分配库位,或者货主指定库区:{}没有库位", ownerId, areaId);
            } else {
                log.warn("当前货主:{} 没有分配库位", ownerId);
            }
            return null;
        } else {
            List<Long> locationIds = ownerLocationEntities.stream().map(item -> item.getLocationId()).collect(Collectors.toList());
            log.info("当前货主:{},包含的全部库位:{}", ownerId, locationIds);
            return locationIds;
        }
    }

    @Override
    public IPage<ReceiptListDetailVO> pageDetail(Page<ReceiptListDetailVO> page, Map data) {
        IPage<ReceiptListDetailVO> iPage = this.baseMapper.selectReceiptListDetail(page, data);
        List<ReceiptListDetailVO> list = iPage.getRecords().stream().map(item -> {
            item.setRecommendLocationPlanEntities(this.getLocationPlanEntities(item.getRecommendLocationPlanId()));
            item.setLocationPlanEntities(this.getLocationPlanEntities(item.getLocationPlanId()));
            return item;
        }).collect(Collectors.toList());
        iPage.setRecords(list);
        return iPage;
    }

    private List<LocationPlanEntity> getLocationPlanEntities(Long locationPlanId) {
        if (locationPlanId == null) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<LocationPlanEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LocationPlanEntity::getGroupId, locationPlanId);
        return this.locationPlanMapper.selectList(wrapper);
    }

    @Override
    public ReceiptListSumVO getSumByMasterId(Long masterId) {
        return this.baseMapper.sumReceiptListDetail(ImmutableMap.of("masterId", masterId));
    }

    @Override
    @Transactional
    public boolean updateById(ReceiptListDTO dto) {
        ReceiptListEntity dbEntity = this.getById(dto.getId());
        if (null != dto.getRealNum()) {
            dto.setRealDifferenceNum(dto.getRealNum() - dbEntity.getPlanNum());
        }
        if (null != dto.getGroundingNum()) {
            dto.setGroundingDifferenceNum(dto.getGroundingNum() - dbEntity.getRealNum());
        }

        boolean result = super.updateById(dto);
        dbEntity = this.getById(dto.getId());
        // 货品数量汇总
        if (null != dto.getPlanNum()) {
            QueryWrapper<ReceiptListEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("IFNULL(sum(plan_num),0) as totalNum")
                    .eq("master_id", dbEntity.getMasterId());

            Map<String, Object> map = this.getMap(queryWrapper);
            Integer totalNum = ((java.math.BigDecimal) map.get("totalNum")).intValue();

            receiptMapper.updateById(ReceiptEntity.builder().id(dbEntity.getMasterId()).planNum(totalNum).build());
        }
        // 实收数量汇总
        if (null != dto.getRealNum()) {
            QueryWrapper<ReceiptListEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("IFNULL(sum(real_num),0) as totalNum,IFNULL(sum(abs(real_difference_num)),0) as differenceNum")
                    .eq("master_id", dbEntity.getMasterId());
            Map<String, Object> map = this.getMap(queryWrapper);
            Integer totalNum = ((java.math.BigDecimal) map.get("totalNum")).intValue();
            Integer differenceNum = ((java.math.BigDecimal) map.get("differenceNum")).intValue();

            LambdaQueryWrapper<ReceivingEntity> receivingUpdateWrapper = new LambdaQueryWrapper<>();
            receivingUpdateWrapper.eq(ReceivingEntity::getMasterId, dbEntity.getMasterId());
            receivingMapper.update(ReceivingEntity.builder().realNum(totalNum).differenceNum(differenceNum).build(), receivingUpdateWrapper);
        }
        // 实上数量汇总
        if (null != dto.getGroundingNum()) {
            QueryWrapper<ReceiptListEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("IFNULL(sum(grounding_num),0) as totalNum,IFNULL(sum(abs(grounding_difference_num)),0) as differenceNum")
                    .eq("master_id", dbEntity.getMasterId());
            Map<String, Object> map = this.getMap(queryWrapper);
            Integer totalNum = ((java.math.BigDecimal) map.get("totalNum")).intValue();
            Integer differenceNum = ((java.math.BigDecimal) map.get("differenceNum")).intValue();

            LambdaQueryWrapper<GroundingEntity> updateWrapper = new LambdaQueryWrapper<>();
            updateWrapper.eq(GroundingEntity::getMasterId, dbEntity.getMasterId());
            groundingMapper.update(GroundingEntity.builder().groundingNum(totalNum).differenceNum(differenceNum).build(), updateWrapper);
        }

        // 实上库位，更新库存
        if (!CollectionUtils.isEmpty(dto.getLocationPlanEntities())) {
            changeStock(dto, dbEntity);
        }
        return result;
    }

    /**
     * 变更库存
     *
     * @param dto
     * @param dbEntity
     */
    private void changeStock(ReceiptListDTO dto, ReceiptListEntity dbEntity) {
        Set<Long> checkSet = new HashSet<>();
        dto.getLocationPlanEntities().forEach(item -> {
            if (checkSet.contains(item.getLocationId())) {
                throw new BizException("库位重复");
            }
            checkSet.add(item.getLocationId());
        });
        // 原来的的方案id
        Map<String, LocationPlanEntity> dbLocationPlanMap;
        Long planId;
        if (null != dbEntity.getLocationPlanId()) {
            planId = dbEntity.getLocationPlanId();
            LambdaQueryWrapper<LocationPlanEntity> planWrapper = new LambdaQueryWrapper<>();
            planWrapper.eq(LocationPlanEntity::getGroupId, planId);
            List<LocationPlanEntity> dbLocationPlan = locationPlanMapper.selectList(planWrapper);
            dbLocationPlanMap = dbLocationPlan.stream().collect(Collectors.toMap(item -> item.getNum() + "-" + item.getLocationId(), item -> item));
        } else {
            planId = IdWorker.getId();
            dbLocationPlanMap = new HashMap<>();
            dbEntity.setLocationPlanId(planId);
            this.updateById(dbEntity);
        }

        ReceiptListEntity finalDbEntity = dbEntity;
        List<LocationPlanEntity> locationPlan = dto.getLocationPlanEntities();
        List<LocationPlanEntity> needSaveLocationPlan = new ArrayList<>();
        log.info(">>>当前明细:{}\n>>>当前方案集合:{}", dbEntity, locationPlan);

        locationPlan.forEach(item -> {
            String planString = item.getNum() + "-" + item.getLocationId();
            if (dbLocationPlanMap.containsKey(planString)) {
                // 如果当前组合存在则无需重复入库
                // 删除掉已经存在的方案，剩余的方案就是需要回滚的。
                dbLocationPlanMap.remove(planString);
                log.info("旧方案明细:{}", item);
            } else {
                // 如果不存在则缓存当前数据 稍后入库
                needSaveLocationPlan.add(item);
                log.info("新方案明细:{}", item);
            }
        });

        // 将之前上架的物品退下来
        log.info("回滚之前上架的方案集合:{}", dbLocationPlanMap.values());
        rollbackOldPlan(dbLocationPlanMap, finalDbEntity);

        // 上架 上架的库存是冻结状态，上架完成将冻结的库存变为正常库存
        log.info("上架的新方案集合:{}", needSaveLocationPlan);
        createNewPlan(finalDbEntity, needSaveLocationPlan);

        // 合并新旧方案
        mergeLocationPlan(dbEntity, planId, locationPlan);

    }

    private void mergeLocationPlan(ReceiptListEntity dbEntity, Long planId, List<LocationPlanEntity> locationPlan) {
        // 删除旧方案信息
        LambdaQueryWrapper<LocationPlanEntity> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(LocationPlanEntity::getGroupId, planId);
        int flag = locationPlanMapper.delete(deleteWrapper);
        log.info("删除旧方案:{}", flag);

        // 插入新的方案信息
        for (LocationPlanEntity locationPlanEntity : locationPlan) {
            locationPlanEntity.setReceiptListId(dbEntity.getId());
            locationPlanEntity.setGroupId(planId);
            flag = locationPlanMapper.insert(locationPlanEntity);
            log.info("插入新方案:{}  {}", flag, locationPlanEntity);
        }
    }

    private void createNewPlan(ReceiptListEntity finalDbEntity, List<LocationPlanEntity> needSaveLocationPlan) {
        needSaveLocationPlan.forEach(item -> {
            // 当前库位的上架数量
            Integer dbGroundingNum = item.getNum();
            // 查询库位信息
            LocationEntity locationEntity = locationMapper.selectById(item.getLocationId());
            if (locationEntity.getFrozen() == 0) {
                log.warn("库位已冻结：{}", locationEntity);
                throw new BizException("库位已冻结，请更换库位");
            }
            // 查询原始库存
            LambdaQueryWrapper<StockEntity> stockWrapper = new LambdaQueryWrapper<>();
            stockWrapper.eq(StockEntity::getLocationId, item.getLocationId()); // 一位一品的情况 库位和库存是一一对应的
            StockEntity stockEntity = stockService.getOne(stockWrapper);

            // 判断原来是否是相同货品，若不是则返回异常
            if (stockEntity != null && !finalDbEntity.getGoodsId().equals(stockEntity.getGoodsId())) {
                log.warn("库位已存在其他类型货品：{}", stockEntity.getGoodsId());
                throw new BizException("库位已存在其他类型货品");
            }

            Integer original = stockEntity == null ? 0 : stockEntity.getTotal();
            Integer originalFree = stockEntity == null ? 0 : stockEntity.getFree();
            Integer stockChange = 0;

            // 此处库存的操作都是操作冻结库存
            LambdaQueryWrapper<StockRecordEntity> stockRecordWrapper = new LambdaQueryWrapper<>();
            stockRecordWrapper.eq(StockRecordEntity::getSourceId, finalDbEntity.getId());
            stockRecordWrapper.eq(StockRecordEntity::getLocationId, item.getLocationId());
            stockRecordWrapper.last("limit 1");
            StockRecordEntity stockRecordEntity = stockRecordMapper.selectOne(stockRecordWrapper);

            if (null == stockRecordEntity) {
                stockRecordEntity = new StockRecordEntity();
                stockRecordEntity.setSourceId(finalDbEntity.getId());
                stockRecordEntity.setLocationId(item.getLocationId());
                stockRecordEntity.setType(StockRecordType.RK.getCode());// 类型入库
                stockRecordEntity.setOriginal(original);
                stockRecordEntity.setOriginalFree(originalFree);
                stockRecordEntity.setWay(StockRecordWay.FROZEN.getCode());
                stockRecordEntity.setAlteration(dbGroundingNum);
                stockRecordEntity.setResult(stockRecordEntity.getOriginal() + stockRecordEntity.getAlteration());
                stockRecordEntity.setResultFree(stockRecordEntity.getOriginalFree());
                stockRecordMapper.insert(stockRecordEntity);
                stockChange = dbGroundingNum;
            } else {
                Integer oldChange = stockRecordEntity.getAlteration();

                stockRecordEntity.setAlteration(dbGroundingNum);
                stockRecordEntity.setResult(stockRecordEntity.getOriginal() + stockRecordEntity.getAlteration());
                stockRecordEntity.setResultFree(stockRecordEntity.getOriginalFree());
                stockRecordMapper.updateById(stockRecordEntity);
                stockChange = dbGroundingNum - oldChange;
            }

            if (stockEntity == null) {
                // 没有原库存 新建库存
                stockEntity = new StockEntity();
                stockEntity.setWarehouseId(locationEntity.getWarehouseId());
                stockEntity.setAreaId(locationEntity.getAreaId());
                stockEntity.setLocationId(locationEntity.getId());
                stockEntity.setOwnerId(finalDbEntity.getOwnerId());
                stockEntity.setGoodsId(finalDbEntity.getGoodsId());
                stockEntity.setTotal(stockRecordEntity.getResult());
                stockEntity.setFree(stockRecordEntity.getResultFree());
            } else {
                // 有库存信息 统计库存记录
                stockEntity.setTotal(stockEntity.getTotal() + stockChange);
            }
            stockService.saveOrUpdate(stockEntity);
        });
    }

    private void rollbackOldPlan(Map<String, LocationPlanEntity> dbLocationPlanMap, ReceiptListEntity finalDbEntity) {
        dbLocationPlanMap.values().forEach(item -> {
            // 当前库位的上架数量
            Integer dbGroundingNum = item.getNum();

            LambdaQueryWrapper<StockRecordEntity> stockRecordWrapper = new LambdaQueryWrapper<>();
            stockRecordWrapper.eq(StockRecordEntity::getSourceId, finalDbEntity.getId());
            stockRecordWrapper.eq(StockRecordEntity::getLocationId, item.getLocationId());
            stockRecordWrapper.eq(StockRecordEntity::getAlteration, dbGroundingNum);
            stockRecordWrapper.last("limit 1");
            StockRecordEntity stockRecordEntity = stockRecordMapper.selectOne(stockRecordWrapper);
            log.info("删除库存变更记录:{}", stockRecordEntity);
            if (null != stockRecordEntity) {
                stockRecordMapper.deleteById(stockRecordEntity.getId());
            }

            LambdaQueryWrapper<StockEntity> stockWrapper = new LambdaQueryWrapper<>();
            stockWrapper.eq(StockEntity::getLocationId, item.getLocationId()); // 一位一品的情况 库位和库存是一一对应的
            StockEntity stockEntity = stockService.getOne(stockWrapper);
            if (null != stockEntity) {
                stockEntity.setTotal(stockEntity.getTotal() - dbGroundingNum);
                stockEntity.setFrozen(stockEntity.getFrozen() - dbGroundingNum);
                log.info("更新库存:{}", stockRecordEntity);
                stockService.saveOrUpdate(stockEntity);
            }
        });
    }

    @Override
    public List goodsIds(Map data) {
        LambdaQueryWrapper<ReceiptListEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(ReceiptListEntity::getGoodsId);
        wrapper.eq(ReceiptListEntity::getMasterId, data.get("masterId"));
        List ids = this.baseMapper.selectObjs(wrapper);
        return ids;
    }
}

